#include <stdio.h>
#include <string.h>
#include <string>
#include <map>
#include <stdlib.h>
#include <cstring>
#include <iostream>
#include <fstream>

#include "Environment.h"
using namespace std;
Environment::Environment(){
}
//map<string, string> myMap;

void Environment::loadConfig() {

    string fname = ".sh142";
    //if (access(fname.c_str(), R_OK) < 0)
      // return;
    myMap.clear();

    ifstream configFile;
    configFile.open (fname.c_str());
    string line;
    if(configFile.is_open()){
        while(!configFile.eof()){
            getline(configFile, line);
            if(!line.empty())
            {
                unsigned long demiliter = line.find_first_of('=');

                string s1 = line.substr(0,demiliter);
                string s2 = line.substr(demiliter+1, line.size()-1);
                myMap[s1] = s2;
            }

        }
    } else {
        cout << "Error opening config file" <<endl;
    }
    return;
}

string Environment::getValue (string vars)
{
    return myMap[vars];
}

void Environment::setValue(string var, string value)
{
    if(var.compare("PATH")==0){
        string pathValue = myMap[var];
        pathValue += ":" + value;
        if(value.at(value.size()-1)!='/')
            pathValue+="/";

        myMap[var] = pathValue;
    }
    else if(var.compare("DATA")==0){
        string dataValue = myMap[var];
        dataValue += ":" + value;
        if(value.at(value.size()-1)!='/')
            dataValue+="/";

        myMap[var] = dataValue;
    }
    else
        myMap[var] = value;
}

bool Environment::getCmdPath(string *cmdName)
{
    string path = myMap["PATH"];


    string newPATHCOMMANDList;
    int x =0;
    while(path[x] != NULL)
    {

        string temp;
        for(int y = 0; x < path.size(); x++, y++){
            if(path[x] == ':')
            {
                break;
            }
            temp.append( 1,  path[x] );

        }
        newPATHCOMMANDList = temp + *cmdName;

        if(fopen(newPATHCOMMANDList.c_str(), "r" )){
            (*cmdName).clear();
            (*cmdName).append(newPATHCOMMANDList);
            return true;


        }
        newPATHCOMMANDList.clear();
        x++;
    }
    //fopen
    return false;
}

bool Environment::getDataPath(string *cmdName)
{
    string path = myMap["DATA"];



    string newDATAPATHList;
    int x =0;
    while(path[x] != NULL)
    {

        string temp;
        for(int y = 0; x < path.size(); x++, y++){
            if(path[x] == ':')
            {
                break;
            }
            temp.append( 1,  path[x] );

        }
        newDATAPATHList = temp + *cmdName;

        if(fopen(newDATAPATHList.c_str(), "r" )){
            (*cmdName).clear();
            (*cmdName).append(newDATAPATHList);
            return true;


        }
        newDATAPATHList.clear();
        x++;
    }
    //fopen
    return false;
}


